class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    public TreeNode invertTree(TreeNode root) {
        //空节点不需要反转，返回空
        if(root==null){
            return null;
        }
        //叶子节点不需要反转，返回根节点值
        if(root.left==null&&root.right==null){
            return root;
        }
        //反转左右子树，开始递归
        TreeNode tmp=root.left;
        root.left=root.right;
        root.right=tmp;
        //递归左子树
        invertTree(root.left);
        //递归右子树
        invertTree(root.right);
        return root;
    }
}